import { themeState } from '@/store/theme'
import { MUI_THEME, THEME } from '@/utils/theme'
import { Theme } from '@types'
import { useRecoilState } from 'recoil'
import { createTheme } from '@mui/material/styles'
import { useEffect, useState } from 'react'

export default function useTheme () {
  const [ theme, setTheme ] = useRecoilState<Theme>(themeState)
  const [ muiTheme, setMuiTheme ] = useState<any>()

  /**
   * 创建 MUI 主题色
   * @param _theme
   * @returns
   */
  const createPaletteByTheme = (_theme:Theme):any => {
    const palette:any = {}
    const keys = Object.keys(MUI_THEME[_theme])
    for (let key of keys) {
      palette[key] = {
        main: MUI_THEME[_theme][key],
      }
    }
    return palette
  }

  /**
   * 主题切换
   * @param _theme
   * @returns
   */
  const changeTheme = (_theme: Theme) => {
    setTheme(_theme)
    localStorage.setItem('theme', _theme)
    setMuiTheme(createTheme({
      palette: { ...createPaletteByTheme(_theme) },
    }))

    const currentTheme = THEME[_theme]
    const themeStyles = Object.keys(currentTheme).map((item:any) => `${item}:${currentTheme[item]}`)
      .join(';')
    document.documentElement.setAttribute('style', themeStyles)
  }

  useEffect(() => {
    let _theme:Theme = 'light'
    const themeMedia = window.matchMedia('(prefers-color-scheme: light)')
    // 获取系统色彩模式
    if (themeMedia.matches) {
      _theme = 'light'
    } else {
      _theme = 'dark'
    }
    // 获取用户设置的色彩模式
    _theme = (localStorage.getItem('theme') as Theme) || _theme
    changeTheme(_theme)
    setMuiTheme(createTheme({
      palette: { ...createPaletteByTheme(_theme) },
    }))
  }, [])

  return { changeTheme, theme, muiTheme }
}
